package com.wxy.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.Scanner;

public class test2 {
    public static void main(String[] args) throws InterruptedException {

        EventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                while (buf.readableBytes() > 0) {
                                    System.out.print((char) buf.readByte());
                                }
                                super.channelRead(ctx, msg);
                            }
                        });
                    }
                })
                .connect("127.0.0.1", 8888);
        Channel channel = channelFuture.sync().channel();
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true){
                String msg = scanner.nextLine();
                if("exit".equals(msg)){
                    channel.close();
                    break;
                }
                ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
                buf.writeBytes(msg.getBytes());
                channel.writeAndFlush(buf);
            }
        },"input").start();

        ChannelFuture channelClose = channel.closeFuture();
        channelClose.addListener((ChannelFutureListener) channelFuture1 -> {
            group.shutdownGracefully();
        });
    }
}
